package routers

import (
	"fmt"
	"github.com/gin-gonic/gin"

	"time"
)

type Option func(engine *gin.Engine)

var options []Option

//注册app的路由配置

func Include(opts ...Option) {
	options = append(options, opts...)
}

// CORSMiddleware 初始化
func CORSMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type,Access-Control-Allow-Headers, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		//c.Writer.Header().Set("Access-Control-Allow-Headers", "*")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE, PATCH")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	}
}

//定义一个中间件

func MiddleWare() gin.HandlerFunc {
	return func(context *gin.Context) {
		t := time.Now()
		fmt.Println("中间件开始执行........")
		//设置变量到contextd的key中
		context.Set("request", "中间件1")
		status := context.Writer.Status()
		fmt.Println("中间件执行完成", status)
		t2 := time.Since(t)
		fmt.Println("时间：", t2)
	}
}
func Init() *gin.Engine {

	r := gin.Default()
	//// 创建基于cookie的存储引擎，secret11111 参数是用于加密的密钥
	//store := cookie.NewStore([]byte("asadqasd"))
	//// 设置session中间件，参数mysession，指的是session的名字，也是cookie的名字
	//// store是前面创建的存储引擎，我们可以替换成其他存储引擎
	//r.Use(sessions.Sessions("mysession", store))
	r.Use(CORSMiddleware())
	r.Use(MiddleWare())
	for _, opt := range options {
		opt(r)
	}
	return r
}
